<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图片变灰</title>
</head>
<body>
  <div class="photo-add">图片变灰</div>
  <input id="file"
         type="file" 
         accept="image/*"
         placeholder="请选择图片">
<script>
  const inputDom = document.getElementById('file')
  var canvas = document.createElement('canvas'); 
  var context = canvas.getContext('2d'); 
  var showimg = document.getElementById('showimg'); 

  inputDom.onchange = function (e) {
    const fileInfo = e.target.files[0]
    const fileReader = new FileReader()
    fileReader.readAsDataURL(fileInfo)

    fileReader.onload = function () {
      const image = new Image()
      image.src = fileReader.result
      image.onload = function() {

        canvas.width = this.width
        canvas.height = this.height
        context.drawImage(this, 0, 0, this.width, this.height)
        const imageData = context.getImageData(0, 0, this.width, this.height)

        const data = imageData.data
        const startTime = performance.now()
        for (let i = 0; i < data.length; i += 4) {
          data[i] = data[i+1] = data[i+2] = (data[i]*76 + data[i+1]*150 + data[i+2]*30) >> 8
        }
        console.log(performance.now() - startTime);
        context.putImageData(imageData, 0, 0)
        
        downLoad(canvas.toDataURL("image/png"), fileInfo.name + '-new.png')
      }
    }
  }
  function downLoad(url, fileName = ''){
    var oA = document.createElement("a");
    oA.download = fileName;
    oA.href = url;
    document.body.appendChild(oA);
    oA.click();
    oA.remove(); 
}
</script>
</body>
</html>